package com.atguigu.spzx.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.constant.RedisKeyConstant;
import com.atguigu.spzx.common.entity.UserInfo;
import com.atguigu.spzx.common.utils.AuthContextUtil;
import com.atguigu.spzx.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * UserLoginAuthInterceptor
 * </p>
 *
 * @author flyduck
 * @since 2023/11/5
 */
public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String userInfoJson = redisTemplate.opsForValue().get(RedisKeyConstant.USER_LOGIN_TOKEN_PREFIX + token);
        //放到threadLocal
        if (StringUtils.isNotBlank(userInfoJson)) {
            AuthContextUtil.setUserInfo(JSON.parseObject(userInfoJson, UserInfo.class));
        }
        return true;
    }
}
